﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using ARS.Control.Attributes;
using ARS.Control.Common.EntityManage;
using ARS.Control.Custom.Entity.Common;
using ARS.Control.Custom.Entity.Fields;
using ARS.PublicTool.DataHandle;

namespace ARS.Control.Custom.Entity.Forms
{
    public class ChoicesDialogForm : Form
    {
        //protected override void OnPreRender(EventArgs e)
        //{
        //    HtmlLink link1 = new HtmlLink();
        //    link1.Attributes["type"] = "text/css";
        //    link1.Attributes["rel"] = "stylesheet";
        //    link1.Attributes["href"] = Page.ClientScript.GetWebResourceUrl(GetType(),
        //                                        ResourcePath.EasyDialog.css);
        //    this.Page.Header.Controls.Add(link1);

        //    this.Page.ClientScript.RegisterClientScriptResource(typeof(ChoicesDialogForm), ResourcePath.EasyDialog.js);
        //    base.OnPreRender(e);
        //}
        private static ChoicesDialogForm choicesDialogForm;

        public ChoicesDialogForm()
        {
            choicesDialogForm = this;
        }

        public string TextList
        {
            get; set;
        }
        public string ValueList
        {
            get;
            set;
        }

        private void Bind(Fields.ChoicesDialogField field,string idList,bool isModify,ref string html)
        {
            //string sql = string.Format("select * from {1} where {0}", where,
               // field.SelectDbSelectConfig.TableName);
            string sql = string.Format("select * from {1} where {2} in ({0})", idList,
field.SelectDbSelectConfig.TableName, field.SelectDbSelectConfig.DataValueField);
            DataTable dt = Factory.DbFactory.DbProvider.Query(sql).Tables[0];
            this.TextList = "|" +
                       string.Join("|", from row in dt.AsEnumerable() select row.Field<string>(field.SelectDbSelectConfig.DataTextField)) +
                       "|";

            if (isModify)
            {
                if (field.IsEncryptKey)
                {
                    this.ValueList = "|" +
                                     string.Join("|",
                                         from row in dt.AsEnumerable()
                                         select Encrypt.EncryptString(row.Field<int>(field.SelectDbSelectConfig.DataValueField).ToString())) +
                                     "|";
                }
                else
                {
                    this.ValueList = "|" +
                                     string.Join("|",
                                         from row in dt.AsEnumerable()
                                         select row.Field<int>(field.SelectDbSelectConfig.DataValueField).ToString()) +
                                     "|";
                }
            }
            html = html.Replace("{{ValueList}}", this.ValueList).Replace("{{TextList}}", this.TextList);
        }

        private EntityKeyInfo keyInfo;
        public override void SetInputValue(EntityKeyInfo keyInfo)
        {
            this.keyInfo = keyInfo;
        }

        protected override void RenderContents(System.Web.UI.HtmlTextWriter output)
        {
            base.RenderContents(output);
            Fields.ChoicesDialogField field = base.Field as Fields.ChoicesDialogField;


            StringBuilder sb = new StringBuilder();
            sb.Append(string.Format("<style type=\"text/css\">{0}</style>", Resource.Res_Entity.easydialog));
            sb.Append(string.Format("<script type=\"text/javascript\">{0}</script>", Resource.Res_Entity.easydialog_min));
            string html =
                Resource.Res_Entity.SelectDialogForm_Html.Replace("{{ListUrl}}", field.ListUrl)
                    .Replace("{{Id}}", this.Field.Html_Control_Name)
                    .Replace("{{value}}", field.DataValueClassName)
                    .Replace("{{text}}", field.DataTextClassName)
                    .Replace("{{MaxChoicesNum}}", field.MaxChoicesNum.ToString());
            if (this.Page.IsPostBack)
            {
                this.ValueList = HttpContext.Current.Request.Form[base.Field.Html_Control_Name];
                this.TextList = HttpContext.Current.Request.Form["SelectDialogForm_text" + base.Field.Html_Control_Name];
            }
            else
            {
                if (field.Value == null)
                {
                    if (this.keyInfo != null)
                    {

                        string where = string.Format("SELECT {0} FROM {1} where {2}={3}", field.SelectDbSelectConfig.DataValueField, field.SaveTableName, field.SaveKeyFieldName, this.keyInfo.Value);

                        this.Bind(field, where, true, ref html);
                    }
                }
                if (field.Value != null)
                {
                    string[] valueList = field.Value.ToString().Split('|'); ;
                    string idlist = string.Join(",", from str in valueList where !string.IsNullOrEmpty(str) select str);
                    if (!string.IsNullOrEmpty(idlist) && !string.IsNullOrEmpty(field.SelectDbSelectConfig.TableName))
                    {

                        this.Bind(field, idlist, false, ref html);

                    }
                }
            }

            html = html.Replace("{{ValueList}}", this.ValueList).Replace("{{TextList}}", this.TextList);

            sb.Append(html);
            sb.Append(Resource.Res_Entity.SelectDialogForm_Js.Replace("{{Id}}", base.Field.Html_Control_Name));
            output.Write(string.Format(base.GetTrHtml(), sb));




            base.RenderContents(output);
        }
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private string DeEncrypt(string value)
        {
            string[] list = value.Split('|');
            value = string.Format("|{0}|", string.Join("|", from str in list where !string.IsNullOrEmpty(str) select Encrypt.DecryptString(str)));
            return value;
        }

        public override object GetInputValue()
        {
            string value = HttpContext.Current.Request.Form[base.Field.Html_Control_Name];
            ChoicesDialogField field = base.Field as ChoicesDialogField;
            if (value != null)
            {
                if (field.IsEncryptKey)
                {
                    value = this.DeEncrypt(value);
                }
            }
            return value;
            
        }
        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="control"></param>
        public void SaveData(Widget.EntityControl control,int newId)
        {
            //this.Page.Controls.
            ChoiceDialogOtherTableModel model = new ChoiceDialogOtherTableModel();
            ChoiceDialogOtherTableHelper choiceDialogOtherTableHelper = new ARS.Control.Custom.Entity.Common.ChoiceDialogOtherTableHelper(model);
            choiceDialogOtherTableHelper.AddOrUpdateHandle(this.Field, newId);
        }

        public class ChoiceDialogOtherTableModel : ARS.Control.Custom.Entity.Interface.IChoiceDialogOtherTableModel
        {
            private ChoicesDialogField field;
            public ChoiceDialogOtherTableModel()
            {
                this.field = (ChoicesDialogField)choicesDialogForm.Field;
            }

            public override string Db_Field_Name()
            {
                return this.field.Db_Field_Name;
            }

            public override string RequestKey()
            {
                return "Id";
            }

            public override string DataTextField()
            {
                return this.field.SelectDbSelectConfig.DataTextField;
            }

            public override string DataValueField()
            {
                return this.field.SelectDbSelectConfig.DataValueField;
            }

            public override bool IsEncryptKey()
            {
                return true;
            }

            public override string SaveTableName()
            {
                return this.field.SaveTableName;
            }

            public override string ValueTableName()
            {
                return this.field.SelectDbSelectConfig.TableName;
            }

            public override string KeyField()
            {
                return field.SaveKeyFieldName;
                //return this.field.Db_Field_Name;
            }
        }
    }
}
